package com.miplus.ccrm.admin.service.impl;

import com.miplus.ccrm.admin.pojo.SysUser;
import com.miplus.ccrm.admin.security.JwtToken;
import com.miplus.ccrm.admin.service.SysUserService;
import com.miplus.ccrm.admin.utils.SpringContextUtil;
import com.miplus.ccrm.common.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Slf4j
@Component
public class JInitService implements CommandLineRunner {
    @Resource
    private JDataService dataService;

    @Resource
    private SysUserService sysUserService;

    @Override
    public void run(String... args){
        log.info("JInitService.run...");

        Environment environment = (Environment) SpringContextUtil.getBean("environment");
        JPubUtils.Init(environment);

        try {
            if (JPubUtils.IsNotEmpty(JPubUtils.jwt_token)) {
                String usrid = JwtToken.getUser(JPubUtils.jwt_token);
                String tokenkey = JPubUtils.getTokenKey(JPubUtils.jwt_token);
                log.info("JInitService.SetUserToken:{}", usrid);

                if (JPubUtils.IsNotEmpty(usrid)) {
                    if (!dataService.hasKey(tokenkey)) {
                        SysUser user = sysUserService.getById(usrid);
                        JSysUser jSysUser = new JSysUser();
                        BeanUtils.copyProperties(user, jSysUser);
                        dataService.set(tokenkey, jSysUser, 0);
                    } else {
                        log.info("JInitService.UserToken hasExist");
                    }
                }
            }
        }
        catch (Exception e){
            log.warn("run.err:",e);
        }
    }
}
